﻿using System;
using Microsoft.Xna.Framework;

namespace Firefly.Framework.Components
{
    public class FrameRateCounter : TextCompositor
    {
        private int _frameCounter;
        private TimeSpan _elapsedTime;

        public int FrameRate { get; private set; }

        public FrameRateCounter(Game game, string fontAsset)
            : base(fontAsset)
        {
            _elapsedTime = TimeSpan.Zero;
        }

        #region IHasContent Members

        public override void LoadContent()
        {
            base.LoadContent();
        }

        public override void UnloadContent()
        {
            base.UnloadContent();
        }

        #endregion

        #region IUpdateable Members

        public override void Update(GameTime gameTime)
        {
            _elapsedTime += gameTime.ElapsedGameTime;

            if (_elapsedTime > TimeSpan.FromSeconds(1))
            {
                _elapsedTime -= TimeSpan.FromSeconds(1);
                FrameRate = _frameCounter;
                _frameCounter = 0;
            }
        }

        #endregion

        #region IDrawable Members

        public override void Draw(GameTime gameTime)
        {
            _frameCounter++;
            Text = string.Format("FPS: {0}", FrameRate);
            base.Draw(gameTime);
        }

        #endregion
    }
}
